package com.sl.au.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.sl.au.entity.Account;
import com.sl.au.entity.Attachment;
import com.sl.au.entity.ExdeBeforeContractWGDetail;
import com.sl.au.entity.InventoryDull;
import com.sl.au.entity.InventoryReduce;
import com.sl.au.entity.Module;
import com.sl.au.entity.Quote;
import com.sl.au.entity.QuoteDevice;
import com.sl.au.entity.QuoteReplacement;
import com.sl.au.entity.User;
import com.sl.au.service.ActivitiService;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.AuditNodeService;
import com.sl.au.service.CustomerService;
import com.sl.au.service.InventoryDullService;
import com.sl.au.service.InventoryReduceService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.au.service.QuoteForeignService;
import com.sl.au.service.QuoteService;
import com.sl.au.service.SaleAreaService;

@RestController
@RequestMapping(value = "/ui/quote")
public class QuoteController extends BaseController {
	@Autowired
	QuoteService quoteService;
	@Autowired
	OptionService optionService;
	@Autowired
	OperateLogService operateLogService;
	@Autowired
	QuoteForeignService quoteForeignService;
	@Autowired
	InventoryReduceService inventoryReduceService;
	@Autowired
	InventoryDullService inventoryDullService;
	@Autowired
	AttachmentService attachmentService;
	@Autowired
	ActivitiService activitiService;
	@Autowired
	AuditNodeService auditNodeService;
	@Autowired
	CustomerService customerService;
	@Autowired
	SaleAreaService saleAreaService;

	// 普通价格单主页面
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = createLayoutView("quote/quoteindex");
		Module module = this.getPageModule("quoteMng");
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String role = a.getRole().getName();
		modelAndView.addObject("userId", userId);
		modelAndView.addObject("role", role);
		modelAndView.addObject("module", module);
		return modelAndView;
	}

	// 添加价格单页面
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public ModelAndView addindex() {
		ModelAndView modelAndView = createLayoutView("quote/quoteAdd");
		Account a = this.getMyAccount();
		User user = a.getUser();
		String userName = a.getUser().getName();
		String superior = a.getUser().getSaleArea().getSuperior();
		String customerCode=customerService.getCustomerCode();
		String businessGroup = "行业";
		modelAndView.addObject("customerCode", customerCode);
		modelAndView.addObject("customers", customerService.getRepository().findAll());
		modelAndView.addObject("saleAreas", saleAreaService.getRepository().findBySuperior(superior));
		modelAndView.addObject("businesses", optionService.getRepository().findByGroup(businessGroup));
		modelAndView.addObject("user", user);
		return modelAndView;
	}

	// 编辑普通价格单页面
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public ModelAndView editindex() {
		ModelAndView modelAndView = createLayoutView("quote/quoteEdit");
		String quoteId = request.getParameter("quoteId");
		if (quoteId != null) {
			Quote quote = quoteService.getRepository().findOne(quoteId);
			modelAndView.addObject("quote", quote);
		}
		Account a = this.getMyAccount();
		User user = a.getUser();
		modelAndView.addObject("user", user);
		return modelAndView;
	}

	/// 查看普通报价单
	@RequestMapping(value = "/see", method = RequestMethod.GET)
	public ModelAndView see() {
		ModelAndView modelAndView = createLayoutView("quote/quote-detail");
		String quoteId = request.getParameter("quoteId");
		if (quoteId != null) {
			Quote quote = quoteService.getRepository().findOne(quoteId);
			modelAndView.addObject("quote", quote);
		}
		Account a = this.getMyAccount();
		User user = a.getUser();
		modelAndView.addObject("user", user);
		return modelAndView;
	}
	
	/**
	 * 清空含税单价总价
	 */
	@RequestMapping(value = "/clearPrice", method = RequestMethod.GET)
	public Map<String, Object> clearPrice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		
		String[] idArray=ids.split(",");
		List<QuoteReplacement>qs=new ArrayList<>();
		for(String id:idArray){
			QuoteReplacement q=this.quoteService.getRepository1().findOne(id);
			q.setDiscount((float)0);
			q.setPrice((float) 0);
			qs.add(q);
		}
		this.quoteService.getRepository1().save(qs);
		map.put("code", 0);
		return map;
	}
	
	@RequestMapping(value = "/changeReplaceIndex", method = RequestMethod.GET)
	public Map<String, Object> changeReplaceIndex(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		int oldIndexOrder = Integer.valueOf(request.getParameter("oldIndexOrder"));
		String quoteId = request.getParameter("quoteId");
		int changeNum = Integer.valueOf(request.getParameter("changeNum"));
		int nowIndex=oldIndexOrder+changeNum;
		QuoteReplacement nowChange=this.quoteService.getRepository1().findOne(id);
		QuoteReplacement preChange=this.quoteService.getRepository1().findByQuoteIdAndIndexOrder(quoteId,nowIndex);
		if(null!=preChange){
			nowChange.setIndexOrder(nowIndex);
			preChange.setIndexOrder(oldIndexOrder);
			this.quoteService.getRepository1().save(nowChange);
			this.quoteService.getRepository1().save(preChange);
		}
		map.put("code", 0);
		return map;
	}

	// 删除普通价格单
	@RequestMapping(value = "/delQuote", method = RequestMethod.GET)
	public Map<String, Object> delQuote(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<Quote> quotes = new ArrayList<Quote>();
		for (int i = 0; i < id.length; i++) {
			String quoteId = id[i];
			Quote quote = new Quote();
			quote.setId(quoteId);
			quotes.add(quote);
			List<Attachment> attachments = attachmentService.getRepository().findByParentId(quoteId);
			attachmentService.getRepository().deleteInBatch(attachments);
			List<QuoteReplacement> quoteReplacements = quoteService.getRepository().findReplacementByQuoteId(quoteId);
			quoteForeignService.getReplacementRepository().deleteInBatch(quoteReplacements);
			List<QuoteDevice> quoteDevices = quoteForeignService.getDeviceRepository()
					.findQuoteDeviceByQuoteId(quoteId);
			if (quoteDevices.size() > 0) {
				for (int n = 0; n < quoteDevices.size(); n++) {
					QuoteDevice quoteDevice = quoteDevices.get(n);
					if (quoteDevice.getInventoryState() != null) {
						if (quoteDevice.getInventoryState().equals("1")) {
							String quoteDeviceId = quoteDevice.getId();
							List<QuoteDevice> quoteDevice1 = quoteForeignService.getDeviceRepository()
									.findLinkDevice(quoteDeviceId);
							quoteDevices.addAll(quoteDevice1);
							List<InventoryReduce> inventoryReduces = inventoryReduceService.getRepository()
									.findByQuoteDeviceId(quoteDeviceId);
							if (inventoryReduces.size() > 0) {
								for (int m = 0; m < inventoryReduces.size(); m++) {
									InventoryReduce inventoryReduce = inventoryReduces.get(m);
									int number = inventoryReduce.getNumber();
									String inventoryDullId = inventoryReduce.getInventoryDullId();
									InventoryDull inventoryDull = inventoryDullService.getRepository()
											.findOne(inventoryDullId);
									int usableNum = inventoryDull.getUsableNum();
									inventoryDull.setUsableNum(usableNum + number);
									inventoryDullService.getRepository().save(inventoryDull);
								}
								inventoryReduceService.getRepository().deleteInBatch(inventoryReduces);
							}
						}
					}
				}

				quoteForeignService.getDeviceRepository().deleteInBatch(quoteDevices);
			}
		}
		///// 插入删除日志
		Account a = this.getMyAccount();
		User user = a.getUser();
		for (Quote b : quotes) {
			Quote old = quoteService.getRepository().findOne(b.getId());
			String content = "删除普通报价单【" + old.getName() + "】";
			operateLogService.log(user, "删除投标", content);
		}
		quoteService.getRepository().deleteInBatch(quotes);
		map.put("code", 0);
		return map;
	}

	// 发起审批页面
	@RequestMapping(value = "/audit/{id}", method = RequestMethod.GET)
	public ModelAndView approveindex(@PathVariable String id) {
		ModelAndView modelAndView = createLayoutView("quote/quoteApprove");
		if (id != null) {
			Quote quote = quoteService.getRepository().findOne(id);
			modelAndView.addObject("quote", quote);
			modelAndView.addObject("quoteName", quote.getName());
			modelAndView.addObject("quoteId", quote.getId());
		}
		return modelAndView;
	}

	// 审批者页面
	@RequestMapping(value = "/audit-view/{taskId}/{id}", method = RequestMethod.GET)
	public ModelAndView auditView(@PathVariable String taskId, @PathVariable String id) {
		ModelAndView modelAndView = createLayoutView("quote/quote-audit-view");
		if (id != null && taskId != null) {
			Quote quote = quoteService.getRepository().findOne(id);
			modelAndView.addObject("quote", quote);
			modelAndView.addObject("quoteName", quote.getName());
			modelAndView.addObject("quoteId", quote.getId());
			modelAndView.addObject("taskId", taskId);
			modelAndView.addObject("auditnodes",
					auditNodeService.getRepository().getNodesById(quote.getProcessInstId(), id));
		}
		return modelAndView;
	}

	// 审批者页面JSON
	@RequestMapping(value = "/audit-view/{taskId}/{id}/json", method = RequestMethod.GET)
	public Map<String, Object> auditViewJSON(@PathVariable String taskId, @PathVariable String id) {
		Map<String, Object> map = new HashMap<>();
		if (id != null && taskId != null) {
			Quote quote = quoteService.getRepository().findOne(id);
			map.put("quote", quote);
			List<QuoteDevice> quoteDevices = quoteService.getQuoteDevice(0, Integer.MAX_VALUE, id, null,
					null);
			List<QuoteReplacement> quoteReplacements = quoteService.getQuoteReplacement(0, Integer.MAX_VALUE, id,
					"createTime", "desc");
			map.put("taskId", taskId);
			map.put("pumps", quoteDevices);
			map.put("others", quoteReplacements);
			map.put("auditNodes", auditNodeService.getAll(quote.getProcessInstId(), id));
		}
		return map;
	}

	// 获得普通价格单的列表
	@RequestMapping(value = "/getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		Module module = this.getPageModule("quoteMng");
		String dataFilter = module.getDataFilter();
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String superior = a.getUser().getSaleArea().getSuperior();
		String areaId = a.getUser().getSaleArea().getId();
		Map<String, String> condition = new HashMap<String, String>();
		condition.put("key", key);
		condition.put("dataFilter", dataFilter);
		condition.put("superior", superior);
		condition.put("areaId", areaId);
		condition.put("userId", userId);
		condition.put("state", "");
		List<Quote> quotes = quoteService.getQuote(start, length, condition, null, null);
		long count = quoteService.getQuoteCount(condition);
		map.put("data", quotes);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	// 获得泵设备明细
	@RequestMapping(value = "/getDevicepage", method = RequestMethod.GET)
	public Map<String, Object> getMainPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String quoteId = request.getParameter("quoteId");
		Long count = null;
		List<QuoteDevice> quoteDevices = quoteService.getQuoteDevice(start, length, quoteId, null, null);
		count = quoteForeignService.getDeviceRepository().findDeviceInQuoteCount(quoteId);
		map.put("data", quoteDevices);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	// 获得其他明细table列表
	@RequestMapping(value = "/getNextOrBeforeOtherDevice", method = RequestMethod.GET)
	public Map<String, Object> getNextOrBeforeOtherDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String nowQuoteId = request.getParameter("nowQuoteId").toString();
		int nowIndex = Integer.parseInt(request.getParameter("nowIndex"));
		int isNext = Integer.parseInt(request.getParameter("isNext"));
		int totalCount = Integer.parseInt(request.getParameter("totalCount"));
		QuoteReplacement quoteReplacement = quoteService.getNextOrBeforeOtherDevice(nowQuoteId,nowIndex,isNext);
		long[] numbers = new long[2];
		String message = "";
		String result = "1";
		if(quoteReplacement == null){
			//数组第一个是当前序号 第二个是总数
			numbers[0] = nowIndex;
			numbers[1] = totalCount;
			result = "0";
			if(isNext == 0){//before
				message = "已经是第一条无法跳转";
			}else{//next
				message = "已经是最后一条无法跳转";
			}
		}else{
			numbers = quoteService.getNowIndexAndCount(quoteReplacement);
		}
		map.put("data", quoteReplacement);
		map.put("count", numbers[1]);
		map.put("index", numbers[0]);
		map.put("message", message);
		map.put("result", result);
		return map;
	}
	

	// 获得其他明细table列表
	@RequestMapping(value = "/getOtherpage", method = RequestMethod.GET)
	public Map<String, Object> getOtherPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String quoteId = request.getParameter("quoteId");
		List<QuoteReplacement> quoteReplacements = quoteService.getQuoteReplacement(start, length, quoteId, null, null);
		long count = quoteService.getRepository().getReplacementCount(quoteId);
		map.put("data", quoteReplacements);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	// 得到当前设备信息数据
	@RequestMapping(value = "/getnowDatapage", method = RequestMethod.GET)
	public Map<String, Object> getnowDataPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String nowDataId = request.getParameter("nowDataId");
		Long count = null;
		List<QuoteDevice> quoteDevices = quoteForeignService.getNowQuoteDevice(start, length, nowDataId, null, null);
		count = quoteForeignService.getDeviceRepository().getNowDeviceCount(nowDataId);
		map.put("data", quoteDevices);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	// 备件数据直接提交归档
		@RequestMapping(value = "/submitfinish", method = RequestMethod.GET)
		public Map<String, Object> submitFinish(HttpServletRequest request) {
			Map<String, Object> map = new HashMap<String, Object>();
			String quoteId = request.getParameter("quoteId");
			Account a = this.getMyAccount();
			User user = a.getUser();
			if (quoteId != null) {
				Quote quote = quoteService.getRepository().findOne(quoteId);
				quote.setAuditState("通过");
				quote.setAuditMsg("备件直接归档");
				quoteService.getRepository().save(quote);
				map.put("quoteId", quoteId);
				String content = "手工归档普通报价单【" + quote.getName() + "】";
				operateLogService.log(user, "手工归档普通报价单", content);
			}
			return map;
		}
		// 备件数据直接提交归档
		@RequestMapping(value = "/cancelstart", method = RequestMethod.GET)
		public Map<String, Object> cancelstart(HttpServletRequest request) {
			Map<String, Object> map = new HashMap<String, Object>();
			String quoteId = request.getParameter("quoteId");
			Account a = this.getMyAccount();
			User user = a.getUser();
			if (quoteId != null) {
				Quote quote = quoteService.getRepository().findOne(quoteId);
				quote.setAuditState("未提交");
				quote.setAuditMsg("备件收回归档");
				quoteService.getRepository().save(quote);
				map.put("quoteId", quoteId);
				String content = "手工收回归档普通报价单【" + quote.getName() + "】";
				operateLogService.log(user, "手工收回归档普通报价单", content);
			}
			return map;
		}

	// 保存复制新增数据
	@RequestMapping(value = "/savePasteAdd", method = RequestMethod.GET)
	public Map<String, Object> savePasteAdd(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String quoteId = request.getParameter("quoteId");
		Account a = this.getMyAccount();
		User user = a.getUser();
		if (quoteId != null) {
			Quote quote = quoteService.getRepository().findOne(quoteId);
			Quote newQuote = new Quote();
			newQuote.setName(quote.getName());
			newQuote.setCustomerName(quote.getCustomerName());
			newQuote.setDeliveryDate(quote.getDeliveryDate());
			newQuote.setMemo(quote.getMemo());
			newQuote.setRatio(quote.getRatio());
			newQuote.setDiscount(quote.getDiscount());
			newQuote.setSum(quote.getSum());
			newQuote.setCostSum(quote.getCostSum());
			newQuote.setAuditState("未提交");
			newQuote.setAssumeSum(quote.getAssumeSum());
			newQuote.setQuoteExplain(quote.getQuoteExplain());
			newQuote.setUser(user);
			quoteService.getRepository().save(newQuote);
			map.put("quoteId", newQuote.getId());
			List<QuoteDevice> quoteDevices = quoteForeignService.getDeviceRepository()
					.findQuoteDeviceByQuoteId(quoteId);
			List<QuoteDevice> newQuoteDevices = new ArrayList<QuoteDevice>();
			for (int i = 0; i < quoteDevices.size(); i++) {
				QuoteDevice quoteDevice = quoteDevices.get(i);
				QuoteDevice newQuoteDevice = new QuoteDevice();
				newQuoteDevice.setProductName(quoteDevice.getProductName());
				newQuoteDevice.setProductModel(quoteDevice.getProductModel());
				newQuoteDevice.setProductType(quoteDevice.getProductType());
				newQuoteDevice.setInventoryState("0");
				newQuoteDevice.setNumber(quoteDevice.getNumber());
				newQuoteDevice.setUnitPrice(quoteDevice.getUnitPrice());
				newQuoteDevice.setPower(quoteDevice.getPower());
				newQuoteDevice.setFlowMaterial(quoteDevice.getFlowMaterial());
				newQuoteDevice.setTransMedia(quoteDevice.getTransMedia());
				newQuoteDevice.setFlux(quoteDevice.getFlux());
				newQuoteDevice.setViscosity(quoteDevice.getViscosity());
				newQuoteDevice.setPumpLift(quoteDevice.getPumpLift());
				newQuoteDevice.setTemperature(quoteDevice.getTemperature());
				newQuoteDevice.setProportion(quoteDevice.getProportion());
				newQuoteDevice.setInPressure(quoteDevice.getInPressure());
				newQuoteDevice.setEffectiveNPSHA(quoteDevice.getEffectiveNPSHA());
				newQuoteDevice.setMustMPSHA(quoteDevice.getMustMPSHA());
				newQuoteDevice.setQuote(newQuote);
				newQuoteDevices.add(newQuoteDevice);
			}
			quoteForeignService.getDeviceRepository().save(newQuoteDevices);
			List<QuoteReplacement> quoteReplacements = quoteService.getRepository().findReplacementByQuoteId(quoteId);
			List<QuoteReplacement> newReplacements = new ArrayList<QuoteReplacement>();
			for (int n = 0; n < quoteReplacements.size(); n++) {
				QuoteReplacement quoteReplacement = quoteReplacements.get(n);
				QuoteReplacement newReplacement = new QuoteReplacement();
				newReplacement.setDeviceName(quoteReplacement.getDeviceName());
				newReplacement.setAmount(quoteReplacement.getAmount());
				newReplacement.setType(quoteReplacement.getType());
				newReplacement.setMaterial(quoteReplacement.getMaterial());
				newReplacement.setUnit(quoteReplacement.getUnit());
				newReplacement.setPrice(quoteReplacement.getPrice());
				newReplacement.setCostPrice(quoteReplacement.getCostPrice());
				newReplacement.setQuote(newQuote);
				newReplacements.add(newReplacement);
			}
			quoteForeignService.getReplacementRepository().save(newReplacements);
			String content = "复制新增普通报价单【" + newQuote.getName() + "】";
			operateLogService.log(user, "复制新增", content);
		}

		return map;
	}

	// 保存价格单
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public Map<String, Object> saveQuote(HttpServletRequest request, @RequestBody Quote quote) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		User user = a.getUser();
		Quote old = quoteService.getRepository().findOne(quote.getId());
		if (old != null) {
			String content = "编辑普通价格单【" + quote.getName() + "】";
			operateLogService.log(user, "编辑投标", content);
		} else {
			String content = "新增普通价格单【" + quote.getName() + "】";
			operateLogService.log(user, "新增投标", content);
		}
		quoteService.getRepository().save(quote);
		String quoteId = quote.getId();
		Date createTime = quote.getCreateTime();
		map.put("code", 0);
		map.put("createTime", createTime);
		map.put("quoteId", quoteId);
		return map;
	}

	// 保存泵设备
	@RequestMapping(value = "/saveDevice", method = RequestMethod.POST)
	public Map<String, Object> saveDevice(HttpServletRequest request, @RequestBody QuoteDevice quoteDevice) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (quoteDevice.getInventoryState() != null) {
			if (quoteDevice.getInventoryState().equals("1")) {
				List<InventoryReduce> inventoryReduces = inventoryReduceService.getRepository()
						.findByQuoteDeviceId(quoteDevice.getId());
				InventoryReduce inventoryReduce = inventoryReduces.get(0);
				int number = inventoryReduce.getNumber();
				String inventoryDullId = inventoryReduce.getInventoryDullId();
				InventoryDull inventoryDull = inventoryDullService.getRepository().findOne(inventoryDullId);
				int usableNum = inventoryDull.getUsableNum();
				inventoryDull.setUsableNum(usableNum + number);
				inventoryDullService.getRepository().save(inventoryDull);
				inventoryReduceService.getRepository().delete(inventoryReduce);
				List<QuoteDevice> linkDevices = quoteForeignService.getDeviceRepository()
						.findLinkDevice(quoteDevice.getId());
				quoteForeignService.getDeviceRepository().deleteInBatch(linkDevices);
				quoteDevice.setInventoryState("0");
			}
		}
		quoteForeignService.getDeviceRepository().save(quoteDevice);
		map.put("nowData", quoteDevice);
		map.put("code", 0);
		return map;
	}

	// 保存其他
	@RequestMapping(value = "/saveOtherDevice", method = RequestMethod.POST)
	public Map<String, Object> saveOther(HttpServletRequest request, @RequestBody QuoteReplacement quoteReplacement) {
		Map<String, Object> map = new HashMap<String, Object>();
		boolean isInit = false;
		String uuid = java.util.UUID.randomUUID().toString();
		if(!StringUtils.hasText(quoteReplacement.getId())) {
			isInit = true;
			quoteReplacement.setId(uuid);
		}
		String quoteId = quoteReplacement.getQuote().getId();
		List<QuoteReplacement> quoteReplacements = quoteService.getQuoteReplacement(0, Integer.MAX_VALUE, quoteId, null, null);
		quoteService.saveOtherDevice(quoteReplacement, quoteReplacements, isInit);
		//exdeBeforeContractService.getExdeBeforeContractWGDetailRepository().save(exdeBeforeContractWGDetail);
		map.put("code", 0);
		map.put("id", quoteReplacement.getId());
		return map;
	}

	// 删除泵 设备细目
	@RequestMapping(value = "/delMainDevice", method = RequestMethod.GET)
	public Map<String, Object> delMainDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<QuoteDevice> quoteDevices = new ArrayList<QuoteDevice>();
		for (int i = 0; i < id.length; i++) {
			String quoteDeviceId = id[i];
			QuoteDevice quoteDevice = quoteForeignService.getDeviceRepository().findOne(quoteDeviceId);
			if (quoteDevice.getLinkDeviceId() != null) {
				QuoteDevice quoteDevice1 = quoteForeignService.getDeviceRepository()
						.findOne(quoteDevice.getLinkDeviceId());
				quoteDevices.add(quoteDevice1);
				List<QuoteDevice> quoteDevices1 = quoteForeignService.getDeviceRepository()
						.findLinkDevice(quoteDevice.getLinkDeviceId());
				quoteDevices.addAll(quoteDevices1);
				List<InventoryReduce> inventoryReduces = inventoryReduceService.getRepository()
						.findByQuoteDeviceId(quoteDevice.getLinkDeviceId());
				if (inventoryReduces.size() > 0) {
					InventoryReduce inventoryReduce = inventoryReduces.get(0);
					int number = inventoryReduce.getNumber();
					String inventoryDullId = inventoryReduce.getInventoryDullId();
					InventoryDull inventoryDull = inventoryDullService.getRepository().findOne(inventoryDullId);
					if (inventoryDull != null) {
						int usableNum = inventoryDull.getUsableNum();
						inventoryDull.setUsableNum(usableNum + number);
						inventoryDullService.getRepository().save(inventoryDull);
					}
					inventoryReduceService.getRepository().deleteInBatch(inventoryReduces);
				}
			} else {
				quoteDevices.add(quoteDevice);
			}

		}
		quoteForeignService.getDeviceRepository().deleteInBatch(quoteDevices);
		map.put("code", 0);
		return map;
	}

	// 删除其他细目
	@RequestMapping(value = "/delOtherDevice", method = RequestMethod.GET)
	public Map<String, Object> delOtherDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		String quoteId = "";
		List<QuoteReplacement> quoteReplacements = new ArrayList<QuoteReplacement>();
		for (int i = 0; i < id.length; i++) {
			String quoteReplacementId = id[i];
			QuoteReplacement quoteReplacement = new QuoteReplacement();
			quoteReplacement.setId(quoteReplacementId);
			quoteReplacements.add(quoteReplacement);
		}
		QuoteReplacement quoteReplacementFirst = quoteForeignService.getReplacementRepository().getOne(quoteReplacements.get(0).getId());
		quoteId = quoteReplacementFirst.getQuote().getId();
		quoteForeignService.getReplacementRepository().deleteInBatch(quoteReplacements);
		quoteService.reCheckQuoteIndex(quoteId);
		map.put("code", 0);
		return map;
	}

	// 得到Quote设备细目（泵和其他）
	@RequestMapping(value = "/getQuoteList", method = RequestMethod.GET)
	public Map<String, Object> getQuoteDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String quoteId = request.getParameter("id");
		List<QuoteDevice> quoteDevices = quoteForeignService.getDeviceRepository().findQuoteDeviceByQuoteId(quoteId);
		List<QuoteReplacement> quoteReplacements = quoteService.getRepository().findReplacementByQuoteId(quoteId);
		map.put("quoteDevices", quoteDevices);// 泵
		map.put("quoteReplacements", quoteReplacements);// other
		return map;
	}

	/**
	 * 提交普通报价审批
	 * 
	 * @param quoteId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/audit/{quoteId}", method = RequestMethod.POST)
	public Map<String, Object> submitAudit(@PathVariable String quoteId, HttpServletRequest request) {

		Map<String, Object> map = new HashMap<>();
		Map<String, String> variables = new HashMap<>();
		Account account = this.getMyAccount();
		int code = -1;
		String name = request.getParameter("name");
		String auditorNumber = request.getParameter("auditorNumber");
		String auditor1 = request.getParameter("auditor1");
		String auditor2 = request.getParameter("auditor2");
		String auditor3 = request.getParameter("auditor3");
		String auditor4 = request.getParameter("auditor4");
		String auditor5 = request.getParameter("auditor5");
		String auditor6 = request.getParameter("auditor6");
		String auditor7 = request.getParameter("auditor7");
		String auditor8 = request.getParameter("auditor8");

		if (null != quoteId && null != account && null != auditorNumber) {
			// 放置流程实例变量
			variables.put("starter", account.getUser().getId());
			variables.put("auditor1", auditor1);
			variables.put("auditor2", auditor2);
			variables.put("auditor3", auditor3);
			variables.put("auditor4", auditor4);
			variables.put("auditor5", auditor5);
			variables.put("auditor6", auditor6);
			variables.put("auditor7", auditor7);
			variables.put("auditor8", auditor8);

			variables.put("auditorNumber", auditorNumber);
			variables.put("auditState", "已提交");
			variables.put("entityName", "quote");
			variables.put("processDefinitionName", "普通价格单");

			variables.put("entityId", quoteId);

			ProcessInstance pInst = activitiService.startProcessInstance("bid", account.getUser().getId(), variables);
			// 流程启动后，将其实例相关信息保存到业务实体中，以便查询
			quoteService.saveProcessStart(quoteId, pInst);
			code = 0;

		}
		map.put("code", code);
		return map;
	}

	/**
	 * 生成普通报价单
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "gen-quote-list/{quoteId}", method = RequestMethod.GET)
	public ResponseEntity<Resource> exportWordData(@PathVariable String quoteId) throws IOException {
		Account account = this.getMyAccount();
		String sender = account.getLoginInfo().getName();
		String filename = quoteService.genQuoteDocx(quoteId, sender);
		Resource file = null;
		String shortName = "报价单.docx";
		if (null != filename) {
			file = attachmentService.loadAsResource(filename);
			String url = file.getURL().toString();
			int a = url.lastIndexOf('/');
			shortName = url.substring(a + 1);
		}
		return ResponseEntity.ok()
				.header(HttpHeaders.CONTENT_DISPOSITION,
						"attachment; charset=UTF-8;filename=\"" + java.net.URLEncoder.encode(shortName, "UTF-8") + "\"")
				.body(file);
	}
	
	/**
	 * 生成备件普通报价单
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "genbj-quote-list/{quoteId}", method = RequestMethod.GET)
	public ResponseEntity<Resource> exportWordBJData(@PathVariable String quoteId) throws IOException {
		Account account = this.getMyAccount();
		User user = account.getUser();
		String sender = account.getLoginInfo().getName();
		String filename = quoteService.genQuoteBJDocx(quoteId, user);
		Resource file = null;
		String shortName = "备件报价单.docx";
		if (null != filename) {
			file = attachmentService.loadAsResource(filename);
			String url = file.getURL().toString();
			int a = url.lastIndexOf('/');
			shortName = url.substring(a + 1);
		}
		return ResponseEntity.ok()
				.header(HttpHeaders.CONTENT_DISPOSITION,
						"attachment; charset=UTF-8;filename=\"" + java.net.URLEncoder.encode(shortName, "UTF-8") + "\"")
				.body(file);
	}
	
	/**
	 * 生成备件合同
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "genbjht-quote-list/{quoteId}", method = RequestMethod.GET)
	public ResponseEntity<Resource> exportWordBJHTData(@PathVariable String quoteId) throws IOException {
		Account account = this.getMyAccount();
		User user = account.getUser();
		String sender = account.getLoginInfo().getName();
		String filename = "";
		try {
			filename = quoteService.genQuoteBJHTDocx(quoteId, user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Resource file = null;
		String shortName = "工矿产品购销合同.docx";
		if (null != filename) {
			file = attachmentService.loadAsResource(filename);
			String url = file.getURL().toString();
			int a = url.lastIndexOf('/');
			shortName = url.substring(a + 1);
		}
		return ResponseEntity.ok()
				.header(HttpHeaders.CONTENT_DISPOSITION,
						"attachment; charset=UTF-8;filename=\"" + java.net.URLEncoder.encode(shortName, "UTF-8") + "\"")
				.body(file);
	}

	// 得到价格单设备
	@RequestMapping(value = "/getEditQuoteDevice", method = RequestMethod.GET)
	public Map<String, Object> getEditQuoteDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String quoteDeviceId = request.getParameter("quoteDeviceId");
		QuoteDevice quoteDevice = quoteForeignService.getDeviceRepository().findOne(quoteDeviceId);
		map.put("quoteDevice", quoteDevice);
		return map;
	}
	// 获得其他明细table列表
		@RequestMapping(value = "/getOtherpageER", method = RequestMethod.GET)
		public Map<String, Object> getOtherpageER(HttpServletRequest request) {
			Map<String, Object> map = new HashMap<String, Object>();
			Map<String, String> condition = new HashMap<String, String>();
			int start = Integer.parseInt(request.getParameter("start"));
			int length = Integer.parseInt(request.getParameter("length"));
			String quoteId = request.getParameter("quoteId");
			String key = request.getParameter("key");
	        if (key == null) {
				key = "";
			}
			key = key.replaceAll("\\s+", "");
			condition.put("quoteId", quoteId);
			condition.put("key", key);
			List<QuoteReplacement> quoteReplacements = quoteService.getQuoteReplacementER(start, length, condition, null, null);
			long count = quoteService.getRepository().getReplacementCountER(quoteId, key);
			map.put("data", quoteReplacements);
			map.put("draw", request.getParameter("draw"));
			map.put("recordsFiltered", count);
			map.put("recordsTotal", count);
			return map;
		}
		// 获得其他明细table列表
		@RequestMapping(value = "/getOtherpageprice", method = RequestMethod.GET)
		public Map<String, Object> getOtherpageprice(HttpServletRequest request) {
			Map<String, Object> map = new HashMap<String, Object>();
			Map<String, String> condition = new HashMap<String, String>();
			int start = Integer.parseInt(request.getParameter("start"));
			int length = Integer.parseInt(request.getParameter("length"));
			String customerName = request.getParameter("customerName");
			String type = request.getParameter("type");
			String deviceName = request.getParameter("deviceName");
			String material = request.getParameter("material");
			if (customerName == null) {
				customerName = "";
			}
			if (type == null) {
				type = "";
			}
			if (deviceName == null) {
				deviceName = "";
			}
			if (material == null) {
				material = "";
			}
			condition.put("customerName", customerName);
			condition.put("type", type);
			condition.put("deviceName", deviceName);
			condition.put("material", material);
			List<QuoteReplacement> quoteReplacements = quoteService.getQuoteReplacementERprice(start, length, condition, null, null);
			long count = quoteService.getRepository().getReplacementCountERprice(type, deviceName, material, customerName);
			map.put("data", quoteReplacements);
			map.put("draw", request.getParameter("draw"));
			map.put("recordsFiltered", count);
			map.put("recordsTotal", count);
			return map;
		}

}
